﻿//using Casamiel.API.Application.Interface;
using Casamiel.API.Application.Services;
using Casamiel.Domain.AggregatesModel;
using ICanPay.Alipay;
using ICanPay.Core;
using ICanPay.Core.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;

namespace Casamiel.API.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    /// 
    [ApiVersionNeutral]
    [Route("Return")]

    public class ReturnController:Controller
    {
        private readonly IGateways gateways;
        private IHttpContextAccessor _httpContextAccesor;
        //private IPaymentRecord _paymentRecord;
        private IicApiService _zhengApiService;
        private readonly IPaymentRecordRepository _paymentRecordRepository;
        public ReturnController(IGateways gateways,IHttpContextAccessor httpContextAccesor
            //,IPaymentRecord paymentRecord
            , IicApiService zhengApiService
            , IPaymentRecordRepository paymentRecordRepository)
        {
            this.gateways = gateways;
            this._httpContextAccesor = httpContextAccesor;
            //this._paymentRecord = paymentRecord;
            this._zhengApiService = zhengApiService;
            this._paymentRecordRepository = paymentRecordRepository;
        }
        /// <summary>
        /// 
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
       
        public async Task<IActionResult> Index()
        {
            SortedDictionary<string, object> sArray = GetRequestGet();
            sArray.Remove("sign");
            sArray.Remove("sign_type");
           var st=  string.Join("&",
                sArray
                .Select(a => $"{a.Key}={a.Value.ToString()}"));
           
            Console.WriteLine(sArray["out_trade_no"]);
            Console.WriteLine(sArray["trade_no"]);

            //var entity = _paymentRecordRepository.GetByTradeNo(sArray["out_trade_no"].ToString());
            //if (entity.State != 1)
            //{
            //    int state = entity.State;
            //    entity.State = 1;
            //    entity.OutTradeNo = sArray["trade_no"].ToString();
            //    entity.PayTime = DateTime.Now;
            //    //var result = _paymentRecord.Update(entity, state);
            //    var a = await _zhengApiService.IcCharge(entity.BillNO, decimal.Parse(entity.Amount.ToString()), 2, entity.OutTradeNo);
            //    var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            //    var n = new { code = a.code, content = rnt, msg = a.msg };
            //    if (a.code == 0 || a.code == 261)
            //    {
            //        var result = _paymentRecordRepository.Update(entity, state);
            //        await _paymentRecordRepository.UnitOfWork.SaveChangesAsync();
            //    }

            //}
            //var entity = _paymentRecord.GetByTradeNo(sArray["out_trade_no"].ToString());
            //if (entity.State != 1)
            //{
            //    int state = entity.State;
            //    entity.State = 1;
            //    entity.OutTradeNo = sArray["trade_no"].ToString();
            //    entity.PayTime = DateTime.Now;
            //    //var result = _paymentRecord.Update(entity, state);
            //    var a = await _zhengApiService.IcCharge(entity.BillNO, decimal.Parse(entity.Amount.ToString()), 2, entity.OutTradeNo);
            //    var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            //    var n = new { code = a.code, content = rnt, msg = a.msg };
            //    if (a.code == 0 || a.code==261)
            //    { 
            //        var result = _paymentRecord.Update(entity, state);
            //    }

            //}
            return new JsonResult(sArray);
           // PaymentNotify notify = new PaymentNotify(gateways);
            //notify.PaymentSucceed += Notify_PaymentSucceed;
            //notify.PaymentFailed += Notify_PaymentFailed;
            ////notify.PaymentFailed += Notify_PaymentFailed;
            //notify.UnknownGateway += Notify_UnknownGateway;

            //// 接收并处理支付通知
            //await notify.ReceivedAsync();
        }



        private SortedDictionary<string, object> GetRequestGet()
        {
          
            SortedDictionary<string, object> sArray = new SortedDictionary<string, object>();
            //NameValueCollection coll;
            //coll = Request.Form;

            foreach (var item in Request.Query.Keys)
            {
                sArray.Add(item, Request.Query[item]);
            }
            //coll = this._httpContextAccesor.HttpContext.Request.QueryString;
            //String[] requestItem = this._httpContextAccesor.HttpContext.Request.Query;
            //for (i = 0; i < requestItem.Length; i++)
            //{
            //    sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
            //}
            return sArray;

        }
    }
}
